using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.Core;

namespace Forum.Business
{
    public class SectionNavbar : ForumUserControl,
        IReplyConverter<GroupReply, GetListOperation>,
        IReplyConverter<SectionReply, GetListOperation>
    {
        protected Repeater tabRepeater;
        private EntityList groupList;
        private EntityList sectionList;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            SectionListRequest sectionRequest = new SectionListRequest();
            sectionRequest.Enabled = (int)EnableStatus.Enable;
            requestBinders.Add(RequestHelper.BuildGetSectionListRequest(this, sectionRequest));
            GroupListRequest groupRequest = new GroupListRequest();
            groupRequest.Enabled = (int)EnableStatus.Enable;
            requestBinders.Add(RequestHelper.BuildGetGroupListRequest(this, groupRequest));

            tabRepeater.ItemDataBound += new RepeaterItemEventHandler(tabRepeater_ItemDataBound);
        }

        private void BindData(EntityList groupList)
        {
            if (tabRepeater != null)
            {
                this.tabRepeater.DataSource = groupList;
                this.tabRepeater.DataBind();
            }
        }

        private void tabRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Group group = e.Item.DataItem as Group;
            Repeater subTabRepeater = e.Item.FindControl("subTabRepeater") as Repeater;

            if (subTabRepeater != null)
            {
                subTabRepeater.DataSource = GetSectionList(group.EntityId.Value);
                subTabRepeater.DataBind();
            }
        }

        #region IReplyConverter<GroupReply,GetListOperation> Members

        public void ConvertReply(GroupReply reply, GetListOperation operation)
        {
            groupList = reply.EntityList;
            BindData(groupList);
        }

        #endregion

        #region IReplyConverter<SectionReply,GetListOperation> Members

        public void ConvertReply(SectionReply reply, GetListOperation operation)
        {
            if (reply != null && reply.EntityList != null)
            {
                sectionList = reply.EntityList;
            }
        }

        #endregion

        #region Private Methods

        private EntityList GetSectionList(int groupId)
        {
            EntityList currentSectionList = new EntityList();
            foreach (Section section in sectionList)
            {
                if (section.GroupId.Value == groupId)
                {
                    currentSectionList.Add(section);
                }
            }
            return currentSectionList;
        }

        #endregion
    }
}